import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/entity/sendcode_entity.dart';
import 'package:oramemo/entity/getinfo_entity.dart';
import '../repositories/auth_repository.dart';
import '../services/storage_service.dart';

class AuthController extends GetxController {
  static AuthController get to => Get.find();
  final AuthRepository _repository = AuthRepository();

  // final _isLoading = false.obs;
  final _isLoggedIn = false.obs;
  final Rx<GetinfoUser?> _user = Rx<GetinfoUser?>(null);

  // bool get isLoading => _isLoading.value;

  bool get isLoggedIn => _isLoggedIn.value;

  GetinfoUser? get user => _user.value;

  @override
  void onInit() {
    super.onInit();
    checkAuthStatus();
  }

  Future<void> checkAuthStatus() async {
    final token = Get.find<StorageService>().getToken();
    _isLoggedIn.value = token != null;
    if (_isLoggedIn.value) {
      await getUserInfo();
    }
  }

  Future<void> login(
      {required String username,
      String? password,
      String? code,
      String? uuid,
      String loginType = '1'}) async {
    try {
      showLoading();
      await Get.find<StorageService>().clearToken();
      _isLoggedIn.value = false;
      _user.value = null;
      final response = await _repository.login(
        username: username,
        password: password,
        code: code,
        uuid: uuid,
        loginType: loginType,
      );

      if (response.isSuccess && response.data != null) {
        await StorageService.to.setToken(response.data!['token']);
        await StorageService.to.setUserName(username);
        _isLoggedIn.value = true;
        await getUserInfo();
        Get.offAllNamed('/home');

      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      dismissLoading();
    }
  }

  Future<void> getUserInfo() async {
    try {
      final response = await _repository.getInfo();
      if (response.isSuccess && response.data != null) {
        _user.value = response.data?.user;
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    }
    return null;
  }

  Future<SendcodeEntity?> sendEmail(String email) async {
    try {
      showLoading();
      final response = await _repository.sendEmail(email);
      if (response.isSuccess) {
        Get.snackbar('Success', 'Email sent successfully');
        return response.data!;
      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      dismissLoading();
    }
    return null;
  }

  Future<void> logout() async {
    try {
      showLoading();
      final response = await _repository.logout();
      if (response.isSuccess) {
        await Get.find<StorageService>().clearToken();
        _isLoggedIn.value = false;
        _user.value = null;
        Get.offAllNamed('/login');
      } else {
        Get.snackbar('Error', response.msg);
      }
    } catch (e) {
      Get.snackbar('Error', e.toString());
    } finally {
      dismissLoading();
    }
  }
}
